package com.kinroy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinroy.reggie.entity.Setmeal;
import com.kinroy.reggie.entity.SetmealDish;
import com.kinroy.reggie.entity.SetmealDto;
import com.kinroy.reggie.mapper.SetmealMapper;
import com.kinroy.reggie.service.SetmealDishService;
import com.kinroy.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService sd;

    @Transactional
    @Override
    public void addWithSetMealDish(SetmealDto setmealDto) {
        boolean save = this.save(setmealDto);
        Long id = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(id);
            return item;
        }).collect(Collectors.toList());
        boolean saveBatch = sd.saveBatch(setmealDishes);


    }

    @Transactional
    @Override
    public SetmealDto showback(Long setMealId) {
        Setmeal byId = this.getById(setMealId);
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, setMealId);
        List<SetmealDish> list = sd.list(lqw);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(byId, setmealDto);
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

    @Transactional
    @Override
    public void upadateWithSetMealDish(SetmealDto setmealDto) {
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Long setMealId = setmealDto.getId();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setMealId);
            return item;
        }).collect(Collectors.toSet());
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, setmealDto);
        boolean remove = sd.remove(lqw);
        for (int i = 0; i < setmealDishes.size(); i++) {
            sd.save(setmealDishes.get(i));
        }
        this.updateById(setmealDto);
    }
}
